<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let arr = ['a', 'b', 'c', 'd'];
    let obj = {a: 1, b: 2, c: 3};

    for(let val of arr){
      console.log(val);
    }

    // 报错：object里没有迭代器
    console.dir(arr); // 有 Symbol(Symbol.iterator)
    console.dir(obj); // 没有 Symbol(Symbol.iterator)
    
    // 实现原理
    // 给obj添加提个迭代器
    obj[Symbol.iterator] = function(){

      let values = Object.values(obj);
      let index = 0;

      return {
        next(){
          if (index >= values.length) {
            return {
              done: true
            }
          } else {
            return {
              done: false,
              value: values[index++]
            }
          }
        }
      }
    }

    for(let val of obj){
      console.log(val);
    }

  </script>
</body>
</html>